package com.example.controller;

import com.example.annotation.MyAuthority;
import com.example.entity.LoginEntity;
import com.example.exception.BaseExceptionHandleAction;
import com.example.exception.LoginException;
import com.example.exception.ServiceException;
import com.example.service.LoginService;
import com.example.service.RedisService;
import com.example.util.LoginHelper;
import com.sun.deploy.net.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.QueryParam;
import java.awt.image.BufferedImage;
import java.io.*;

@RestController
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private RedisService redisService;

    @MyAuthority(value = MyAuthority.LoginType.IS_LOGIN)
    @RequestMapping("/addUser")
    public void addUser(LoginEntity entity)
    {
        //先查询用户名存不存在，存在则抛出异常，放在service层里面就需要抛异常，放在control里面，control抛异常
        loginService.addUser(entity);
    }
    //真实项目中登录不能用GET方式，因为账号密码不能在url里面被看到
    @MyAuthority(value = MyAuthority.LoginType.ANONYMOUSLY)
    @RequestMapping("/login")
    public void login(@RequestParam String name , @RequestParam String password)
    {
        LoginEntity realPas = loginService.queryByName(name);
        if (null==realPas)
            throw new LoginException().createException("1115");
        if (password.equals(realPas.getPassword()))
        {
            //此处可以setcookie
            LoginHelper.setCookieUserInfo(realPas);
            //存入缓存
            redisService.setValue(realPas.getId().toString(),realPas,30);
            return;
        }
        throw  ServiceException.createException("1114");
    }
    @RequestMapping("/logName")
    public String getNameById(@RequestParam Long id)
    {
        return loginService.getUserNameById(id);
    }



    @MyAuthority(value = MyAuthority.LoginType.IS_LOGIN)
    @RequestMapping("/cookie")
    @ResponseBody
    public String cookie(@CookieValue(value = "uid",required = true) String jessionId)
    {
        return  jessionId;
    }

    @MyAuthority(value = MyAuthority.LoginType.IS_LOGIN)
    @RequestMapping("/logout")
    public void logout()
    {
        redisService.delKey(LoginHelper.getUserInfo().getId().toString());
        LoginHelper.clearCookie();
    }
    @MyAuthority(value = MyAuthority.LoginType.IS_LOGIN)
    @RequestMapping("/deleteUser")
    public void deleteUser(String name ,String password)
    {
        LoginEntity realPas = loginService.queryByName(name);
        if (null!=realPas)
            loginService.deleteUser(realPas);
        throw  ServiceException.createException("1114");
    }



}
